<template>
  <div v-loading="loading" class="app-container">
    <div class="head-container">
      <el-input v-model="filterText" placeholder="输入类目进行过滤" clearable style="width: 200px" />
      <el-button v-if="checkRole()" size="mini" type="primary" style="margin-bottom: 5px; margin-left: 0px" round @click="downloadExcel">导出</el-button>
    </div>
    <div style="padding-top: 5px">
      <el-container style="background-color: white">
        <el-aside style="background-color: white">
          <div class="handle">
            <div>
              <el-button type="text" @click="expandAll">全展开</el-button>
              <el-button type="text" @click="collapseAll">全收起</el-button>
            </div>
            <div>
              <el-button type="text" class="el-icon-refresh" @click="initTableData(true)">刷新</el-button>
            </div>
          </div>
          <div style="font-size: 13px">可拖动类目进行排序，重新排序后请发布变更！</div>
          <div class="tableHead">
            <div>类目名称</div>
            <div>状态</div>
            <div v-if="channelId === '12'">是否展示</div>
            <div>{{ channelId === '06' ? ' ' : '操作' }}</div>
          </div>
          <div v-loading="refreshLoading">
            <el-tree
              ref="categoryTree"
              draggable
              highlight-current
              node-key="categoryId"
              :data="data"
              :props="defaultProps"
              :allow-drop="allowDrop"
              :render-content="renderContent"
              :expand-on-click-node="false"
              :filter-node-method="filterNode"
              :current-node-key="currentKey"
              :default-expanded-keys="defaultExpandKeys"
              :allow-drag="allowDrag"
              @node-drop="handleDrop"
            />
          </div>
        </el-aside>
        <el-main v-if="channelId !== '06'">
          <el-button v-if="checkRole()" size="mini" type="success" style="float: right" round @click="doPublish">发布变更</el-button>
          <el-button v-if="checkRole()" size="mini" type="text" style="float: right; margin-left: 20px" round @click="addOneLevel()">新增一级目录</el-button>
          <div v-if="param">
            <h3>{{ title }}</h3>
            <el-form ref="dataForm" :model="param" :rules="rules" size="small" label-width="180px">
              <el-form-item label="类目类型" prop="categoryType">
                <el-radio v-model="param.categoryType" :label="1" border>常规类目</el-radio>
                <el-radio v-model="param.categoryType" :label="2" border>临时\促销类目</el-radio>
              </el-form-item>
              <el-form-item label="类目名称" prop="categoryName">
                <el-input v-model="param.categoryName" size="mini" style="width: 280px" />
                <el-popover style="margin-left: 10px" placement="bottom" trigger="click">
                  一级类目名称长度不能超过16个字节，二三级类目名称长度不能超过30个字节(一个汉字占3个字节，一个英文字母或数字占1个字节)
                  <i slot="reference" class="el-icon-question" />
                </el-popover>
              </el-form-item>
              <el-form-item v-if="param.channelId === '12'" label="是否展示" prop="showFlag">
                <el-checkbox v-model="param.showFlag" size="mini" :true-label="1" :false-label="0" />
              </el-form-item>
              <el-form-item v-if="param.channelId === '12'" label="是否极速达" prop="jsdFlag">
                <el-checkbox v-model="param.jsdFlag" size="mini" :true-label="1" :false-label="0" :disabled="param.cbecFlag === 1" />
              </el-form-item>
              <el-form-item v-if="param.channelId === '12'" label="是否全城配" prop="qcpFlag">
                <el-checkbox v-model="param.qcpFlag" size="mini" :true-label="1" :false-label="0" :disabled="param.cbecFlag === 1" />
              </el-form-item>
              <el-form-item v-if="param.channelId === '12'" label="是否全球购" prop="cbecFlag">
                <el-checkbox v-model="param.cbecFlag" size="mini" :true-label="1" :false-label="0" :disabled="param.qcpFlag === 1 || param.jsdFlag === 1" />
              </el-form-item>
              <el-form-item v-if="!param.hasChildren" label="是否叶子节点" prop="childFlag">
                <el-checkbox v-model="param.childFlag" size="mini" :true-label="1" :false-label="0" disabled />
              </el-form-item>
              <el-form-item v-if="param.channelId === '12' && param.categoryPidStr === '0'" label="类目图片">
                <div class="categoryImg">
                  <el-image
                    v-if="param.categoryImgIntraNetUrl || param.categoryImgExtraNetUrl"
                    :src="(param.categoryImgIntraNetUrl || param.categoryImgExtraNetUrl) | transImgUrl"
                  />
                  <div class="del">
                    <i v-if="(param.categoryImgIntraNetUrl || param.categoryImgExtraNetUrl) && checkRole()" class="el-icon-delete" @click="doDeleteImgUrl" />
                  </div>
                </div>
                <el-upload
                  v-if="checkRole() && !(param.categoryImgIntraNetUrl || param.categoryImgExtraNetUrl)"
                  ref="upload"
                  :auto-upload="false"
                  :limit="1"
                  :multiple="false"
                  :on-exceed="handleExceed"
                  :on-change="handleOnChange"
                  :on-remove="handleOnRemove"
                  :file-list="param.fileList"
                  list-type="picture"
                  style="width: 300px"
                  action="#"
                >
                  <el-button size="mini" type="primary">点击选择上传类目图片</el-button>
                  <div slot="tip" class="el-upload__tip">只能上传图片文件(jpg,png,jpeg)，且大小不超过500KB，尺寸150px*150px</div>
                </el-upload>
              </el-form-item>
              <el-form-item>
                <el-button v-if="param.categoryId !== 0 && checkRole()" size="mini" type="primary" @click="doSubmit">保存</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-main>
      </el-container>
    </div>
  </div>
</template>

<script>
// import { parseTime } from '@/utils/index'
import { queryTreeList, deleteOne, doSort, saveOne, publish } from '@/api/coi/category/category'
import { Message } from 'element-ui'
// import { previewFile } from '@/utils/item'
import { doDownload } from '@/api/olm/download'
import { upLoadImage } from '@/api/coi/store-list'
import { authentication } from '@/utils/processingData.js'

export default {
  name: 'StoreList',
  filters: {
    transImgUrl(url) {
      return authentication(url)
    }
  },
  data() {
    var validateCategoryName = (rule, value, callback) => {
      if (this.param.categoryLevel === 1 && value.length > 16) {
        callback(new Error('类目名称过长'))
      } else if (this.param.categoryLevel > 1 && value.length > 30) {
        callback(new Error('类目名称过长'))
      } else {
        callback()
      }
    }
    return {
      title: '',
      parent: this,
      loading: false,
      data: [],
      param: null,
      channelId: '12',
      channelOptions: [],
      defaultProps: { children: 'children', label: 'categoryName' },
      rules: {
        categoryType: [{ required: true, message: '请选择类目类型', trigger: 'change' }],
        categoryName: [
          { required: true, message: '请填写类目名称', trigger: 'blur' },
          { validator: validateCategoryName, trigger: 'blur' }
        ]
      },
      filterText: '',
      currentKey: '',
      defaultExpandKeys: [],
      refreshLoading: false
    }
  },
  watch: {
    filterText(val) {
      this.$refs.categoryTree.filter(val)
    }
  },
  mounted() {
    let channelId = this.$route.path
    channelId = channelId.split('/')
    this.channelId = channelId[channelId.length - 1]
    this.changeChannel(this.channelId)
  },
  methods: {
    changeChannel(channelId) {
      this.channelId = channelId
      this.param = null
      if (this.channelId) {
        this.initTableData()
      } else {
        this.data = null
      }
    },
    checkRole() {
      if (this.channelId === '12') {
        return this.hasRole(['R017001', 'R017017', 'R017009'])
      } else if (this.channelId === '07') {
        return this.hasRole(['R017001', 'R017018', 'R017009'])
      } else {
        return false
      }
    },
    filterNode(value, data) {
      if (!value) return true
      return data.categoryName.indexOf(value) !== -1
    },
    // 初始化列表数据
    initTableData(bol = false) {
      if (bol) {
        this.param = null
        this.refreshLoading = true
      }
      if (!bol) this.loading = true
      queryTreeList({ channelId: this.channelId }).then(
        (res) => {
          const _hasChildren = res && res.result
          // const node = [{ categoryId: 0, categoryName: '根节点', children: res.result, hasChildren: _hasChildren, id: 0 }]
          this.data = _hasChildren
          this.loading = false
          this.refreshLoading = false
        },
        (error) => {
          console.log(error)
          this.loading = false
          this.refreshLoading = true
        }
      )
    },
    // 删除类目
    doDeleteOne(row) {
      this.$confirm('确认删除该类目?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true
        deleteOne(row).then(
          (_) => {
            this.initTableData()
            Message({
              message: '操作成功。',
              type: 'success',
              duration: 3 * 1000
            })
            this.param = null
            this.loading = false
          },
          (error) => {
            console.log(error)
            this.loading = false
          }
        )
      })
    },
    forArr(node, isExpand) {
      node.expanded = isExpand
      node.childNodes.forEach((childNode) => {
        childNode.expanded = isExpand
        if (childNode.childNodes && childNode.childNodes.length > 0) {
          this.forArr(childNode, isExpand)
        }
      })
    },
    // 全展开
    expandAll() {
      const node = this.$refs.categoryTree.store.root
      this.forArr(node, true)
    },
    // 全收起
    collapseAll() {
      const node = this.$refs.categoryTree.store.root
      this.forArr(node, false)
    },
    // 新增一级类目
    addOneLevel() {
      this.title = '新增一级类目'
      this.param = {
        channelId: this.channelId
      }
      this.$nextTick(() => {
        this.param = {
          pId: 0,
          qcpFlag: 0,
          jsdFlag: 0,
          cbecFlag: 0,
          showFlag: 1,
          categoryPid: 0,
          categoryType: 1,
          categoryPidStr: '0',
          channelId: this.channelId,
          childFlag: 0
        }
      })
    },
    // 导出
    downloadExcel() {
      if (this.channelId) {
        this.loading = true
        let name = '沃尔玛到家'
        if (this.channelId === '07') {
          name = '京东到家'
        }
        if (this.channelId === '06') {
          name = '京东沃选'
        }
        doDownload(process.env.VUE_APP_BASE_API6 + '/category/downloadExcel', { channelId: this.channelId }, name + '店内类目.xlsx').then(
          (_) => {
            this.loading = false
          },
          (error) => {
            console.log(error)
            this.loading = false
          }
        )
      } else {
        Message({
          message: '请选择渠道后再进行导出操作。',
          type: 'warning',
          duration: 3 * 1000
        })
      }
    },
    categoryNameStyle(row) {
      let sty = ''
      if (row.categoryLevel === 1) {
        sty += 'font-weight:bold;font-size:16px;'
      } else if (row.categoryLevel === 2) {
        sty += 'font-weight:bold;'
      }
      if (row.dataStatus === -1) {
        sty += 'color:#fc1111'
      }
      return sty
    },
    // 是否可以拖入
    allowDrop(draggingNode, dropNode, type) {
      if (type === 'inner') {
        return false
      } else {
        if (draggingNode.parent.id === dropNode.parent.id) {
          return true
        } else {
          return false
        }
      }
    },
    allowDrag(draggingNode) {
      if (!this.checkRole()) return false
      const childIds = []
      let allowSort = true
      draggingNode.parent.childNodes.forEach((obj) => {
        childIds.push(obj.data.categoryIdStr)
        if (obj.data.publishFlag !== 1) allowSort = false
      })
      window.console.log(draggingNode, allowSort)
      if (!allowSort) {
        Message({
          message: '同级类目下存在未发布或发布失败的类目，不可排序。请先发布，然后进行排序！',
          type: 'warning',
          duration: 3 * 1000
        })
        return false
      }
      return true
    },
    // 拖拽成功后触发
    handleDrop(draggingNode, dropNode, dropType, ev) {
      const childIds = []
      dropNode.parent.childNodes.forEach((obj) => {
        childIds.push(obj.data.categoryIdStr)
      })
      const pId = dropNode.parent.parent === null ? '0' : dropNode.parent.data.categoryIdStr
      doSort({ channelId: this.channelId, pId: pId, childIds: childIds }).then(
        (_) => {
          Message({
            message: '操作成功。',
            type: 'success',
            duration: 3 * 1000
          })
          this.initTableData()
          this.param = null
        },
        (error) => {
          console.log(error)
        }
      )
    },
    // 文件超出个数限制时的钩子
    handleExceed(file, fileList) {
      Message({
        message: '文件上传数量限制为1个。',
        type: 'warning',
        duration: 3 * 1000
      })
    },
    // 文件变动的钩子
    handleOnChange(file, fileList) {
      if (!(file.raw.type === 'image/png' || file.raw.type === 'image/jpg' || file.raw.type === 'image/jpeg')) {
        Message({
          message: '图片格式错误。',
          type: 'warning',
          duration: 3 * 1000
        })
        fileList.pop()
      }
      var size = file.size / 1024
      if (size > 500) {
        Message({
          message: '图片文件大小必须小于500KB。',
          type: 'warning',
          duration: 3 * 1000
        })
        fileList.pop()
      }
      const _this = this
      const width = 150
      const height = 150
      const _URL = window.URL || window.webkitURL
      const image = new Image()
      image.onload = function () {
        const valid = image.width === width && image.height === height
        if (valid) {
          _this.param.fileList = fileList
          // this.$refs.dataForm.validate()
        } else {
          Message({
            message: '图片尺寸必须是150✖150像素！',
            type: 'warning',
            duration: 3 * 1000
          })
          fileList.pop()
        }
      }
      image.src = _URL.createObjectURL(file.raw)
      this.$refs.dataForm.validate()
    },
    // 删除文件时的狗子
    handleOnRemove(file, fileList) {
      fileList.pop()
      this.param.fileList = fileList
      this.$refs.dataForm.validate()
    },
    // 图片上传
    uploadImg() {
      this.loading = true
      return new Promise((resolve, reject) => {
        if (!this.param.fileList || this.param.fileList.length < 1) {
          this.loading = false
          resolve(null)
        }
        const file = this.param.fileList[0]
        var formData = new FormData()
        formData.append('file', file.raw)
        upLoadImage(formData)
          .then((res) => {
            if (res) {
              const filePath = res.result.baseDownloadUrl + '/' + res.result.uploadId
              if (filePath) {
                this.param.fileList.pop()
                resolve(filePath)
              }
            }
            this.loading = false
            resolve(null)
          })
          .catch((err) => {
            this.loading = false
            reject(err)
          })
      })
    },
    // 树状控件渲染
    renderContent(h, { node, data, store }) {
      // <span on-click={ () => this.doEdit(data) } >{node.label}{data.publishFlag === 0 ? '(未发布)' : ''}</span>
      const spant = data.publishFlag === 0 ? 'custom-tree-node-update' : data.publishFlag === 2 ? 'custom-tree-node-update' : 'custom-tree-node'
      const status = this.channelId === '12' ? 'status2' : 'status'
      const spant2 =
        data.publishFlag === 0 ? `${status} yellow` : data.publishFlag === 2 ? `${status} red` : data.publishFlag === 3 ? `${status} blue` : `${status} green`
      const spant3 = this.channelId === '06' ? 'display: none' : ''
      const spant4 = this.channelId !== '12' ? 'display: none' : ''
      return (
        <span class={spant}>
          <span class={'column1'} on-click={() => this.doEdit(data)}>
            {node.label}
          </span>
          <span class={spant2}>
            {data.publishFlag === 0 ? (
              '未发布'
            ) : data.publishFlag === 2 ? (
              <el-tooltip placement='top'>
                <div slot='content'>{'发布失败，' + data.publishFailMsg}</div>
                <span>发布失败</span>
              </el-tooltip>
            ) : data.publishFlag === 3 ? (
              '发布中'
            ) : (
              '已发布'
            )}
          </span>
          <span style={spant4} class={'showFlag'}>
            {data.showFlag === 1 ? '展示' : '不展示'}
          </span>
          <span style={spant3}>
            {data.categoryLevel < 3 && this.checkRole() ? (
              <el-button size='mini' type='text' on-click={() => this.doAdd(data)}>
                新增子分类&nbsp;&nbsp;
              </el-button>
            ) : (
              ''
            )}
            {data.categoryId !== 0 && this.checkRole() ? (
              <el-button size='mini' type='text' on-click={() => this.doDeleteOne(data)}>
                删除
              </el-button>
            ) : (
              ''
            )}
          </span>
        </span>
      )
    },
    // 点击新增下级节点操作
    doAdd(data) {
      if (data.publishFlag === 0 || data.publishFlag === 2) {
        Message({
          message: `父类目还未发布或发布失败不可创建子类目，请先发布，然后创建子类目！`,
          type: 'warning',
          duration: 3 * 1000
        })
        return
      }
      const _param = {}
      _param.channelId = this.channelId
      this.param = _param
      this.title = '新增下级类目'
      this.$nextTick(() => {
        this.param = {
          pId: data.id,
          qcpFlag: 0,
          jsdFlag: 0,
          showFlag: 1,
          cbecFlag: data.cbecFlag,
          categoryPid: data.categoryId,
          categoryType: data.categoryType,
          channelId: this.channelId,
          childFlag: this.channelId === '12' && data.categoryPidStr !== '0' ? 1 : 0
        }
      })
    },
    // 点击编辑操作
    doEdit(data) {
      this.param = JSON.parse(JSON.stringify(data))
      this.title = '编辑类目'
    },
    // 删除图片
    doDeleteImgUrl() {
      this.param.categoryImgIntraNetUrl = null
      this.param.categoryImgExtraNetUrl = null
    },
    checkCategoryName() {
      if (this.param.categoryPid === 0) {
        if (this.title === '新增一级类目') {
          let bol = true
          for (let i = 0; i < this.data.length; i++) {
            const item = this.data[i]
            if (item.categoryName === this.param.categoryName) {
              this.$message({
                type: 'warning',
                message: '一级类目不能有重复的类目名!'
              })
              bol = false
              break
            }
          }
          if (!bol) return bol
        }
      }
      if (this.channelId === '12' && this.param.qcpFlag === 0 && this.param.jsdFlag === 0 && this.param.cbecFlag === 0) {
        Message({
          message: '极速达, 全城配, 全球购必须选择其一！',
          type: 'warning',
          duration: 3 * 1000
        })
        return false
      }
      return true
    },
    // 提交
    doSubmit() {
      if (!this.checkCategoryName()) return
      this.$confirm('确认提交?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$refs.dataForm.validate((valid) => {
          if (valid) {
            this.uploadImg().then((url) => {
              if (url) this.param.categoryImgIntraNetUrl = url
              if (
                this.channelId === '12' &&
                this.param.categoryPid === 0 &&
                this.param.categoryImgIntraNetUrl === null &&
                this.param.categoryImgExtraNetUrl === null
              ) {
                Message({
                  message: '一级类目图片不能为空！',
                  type: 'warning',
                  duration: 3 * 1000
                })
                return
              }
              saveOne(this.param).then(
                (_) => {
                  this.defaultExpandKeys = this.title === '新增下级类目' || this.title === '新增一级类目' ? [this.param.categoryPid] : [this.param.categoryId]
                  this.initTableData()
                  Message({
                    message: '操作成功。',
                    type: 'success',
                    duration: 3 * 1000
                  })
                  this.currentKey = JSON.parse(
                    JSON.stringify(this.title === '新增下级类目' || this.title === '新增一级类目' ? this.param.categoryPid : this.param.categoryId)
                  )
                  this.loading = false
                },
                (error) => {
                  console.log(error)
                  this.loading = false
                }
              )
            })
          }
        })
      })
    },
    // 发布
    async doPublish() {
      this.$confirm('是否发布当前所选渠道的所有变更?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          try {
            this.loading = true
            publish({ channelId: this.channelId }).then(() => {
              if (this.param) this.defaultExpandKeys = [this.param.categoryId]
              this.initTableData()
              Message({
                message: '操作成功！',
                type: 'success',
                duration: 3 * 1000
              })
              setTimeout(() => {
                this.param = null
              }, 500)
            })
          } finally {
            this.loading = false
          }
        })
        .catch(() => {})
    }
  }
}
</script>
<style lang="scss">
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 4px;
  position: relative;
}
.custom-tree-node-update {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 4px;
  /* color: red; */
}
.status {
  display: block;
  width: 150px;
  text-align: center;
  position: absolute;
  right: 180px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
.status2 {
  display: block;
  width: 150px;
  text-align: center;
  position: absolute;
  right: 262px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
.showFlag {
  display: block;
  width: 150px;
  text-align: center;
  position: absolute;
  right: 130px;
}
.red {
  color: red;
}
.yellow {
  color: rgb(255, 166, 0);
}
.green {
  color: rgb(3, 128, 3);
}
.blue {
  color: rgb(0, 110, 255);
}
</style>
<style lang="scss" scoped>
.head-container {
  margin-left: 20px;
}
.el-aside {
  overflow: hidden !important;
  width: 600px !important;
}
.handle {
  display: flex;
  justify-content: space-between;
}
.tableHead {
  width: 100%;
  height: 35px;
  line-height: 35px;
  display: flex;
  justify-content: space-around;
  border: 1px solid gray;
  background-color: #eee;
}
/deep/ .el-form-item__content {
  display: flex;
  align-items: center;
}
.el-icon-question {
  margin-left: 10px;
  cursor: pointer;
  font-size: 20px;
}
.categoryImg {
  position: relative;
  &:hover .del {
    display: block;
    height: 18px;
  }
  .del {
    line-height: 15px;
    border-radius: 1px;
    text-align: center;
    width: 100%;
    height: 0;
    overflow: hidden;
    position: absolute;
    left: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.3);
    cursor: pointer;
    color: #fff;
    font-size: 14px;
    transition: linear all 0.3s;
    .el-icon-delete {
      margin: 2px 0;
    }
  }
  /deep/.el-image {
    width: 100px;
    height: 100px;
  }
}
.el-icon-refresh {
  font-size: 18px;
}
</style>
